import time
import os
import json
import requests
from urllib.parse import urlencode
from urllib.request import urlretrieve


def getPage(offset):
    '''爬取web信息'''
    # 定义参数
    params = {
        'tn': 'resultjson_com',
        'ipn': 'rj',
        'ct': '201326592',
        'is': '',
        'fp': 'result',
        'queryWord': kw,
        'cl': '2',
        'lm': '-1',
        'ie': 'utf-8',
        'oe': 'utf-8',
        'adpicid': '',
        'st': '',
        'z': '',
        'ic': '',
        'word': kw,
        's': '',
        'se': '',
        'tab': '',
        'width': '',
        'height': '',
        'face': '',
        'istype': '',
        'qc': '',
        'nc': '1',
        'fr': '',
        'pn': offset,
        'rn': '30',
        'gsm': str(hex(offset))[2:],
        '1536636794480': '',
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
    }
    # 初始化url地址
    url = 'http://image.baidu.com/search/acjson'
    try:
        res = requests.get(url, headers=headers, params=params)
        if res.status_code == 200:
            return res.json()
        else:
            return None
    except:
        return None


def getImage(json):
    '''解析数据，获取图片信息'''
    data = json.get('data')
    if data:
        a = 1
        for item in data:
            if item.get('thumbURL'):
                yield {
                    'image': item.get('thumbURL'),
                    'title': kw + '_' + str(offset) + '_' + str(a),
                }
                a += 1


def saveImage(item):
    '''保存图片'''
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
    }
    # 图片的存储路径
    path = os.path.join('./mypic2/', kw)
    if not os.path.exists(path):
        os.mkdir(path)
    # 图片的路径处理
    local_image_url = item.get('image')
    save_pic = path + '/' + item.get('title') + '.jpg'
    # 储存图片
    urlpic = requests.get(local_image_url, headers=headers).content
    with open(save_pic, 'wb') as f:
        f.write(urlpic)


def main(offset):
    '''主程序'''
    json = getPage(offset)
    for item in getImage(json):
        saveImage(item)


if __name__ == '__main__':
    kw = input('请输入需要查询的文字：')
    for i in range(5):
        print('正在查询' + str(i + 1) + '页')
        offset = i * 30
        main(offset)
        print('end...' + str(i + 1) + '页')
        time.sleep(2)
